<!DOCTYPE html>
<html lang="en">  
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<title>发送口令红包</title> 
</head>
<link rel="stylesheet" href="__CSS__/sendPackage.min.css">
<body>
	<div id="app" v-cloak>		
		<div class="password">
			<span>语音口令</span>
			<input type="text" placeholder="谢谢老板" v-model="text" @input="Input">
		</div>
		<div class="totalMoney">
			<span>奖励总额</span>
			<p><input type="number" v-model="price"> 元</p>
		</div>
		<div class="choosePrice">
			<span :class="{'active':type==1}" @click="type=1,price=1">1 元</span>
			<span :class="{'active':type==2}" @click="type=2,price=5">5 元</span>
			<span :class="{'active':type==3}" @click="type=3,price=10">10 元</span>
			<span :class="{'active':type==4}" @click="type=4,price=50">50 元</span>
		</div> 
		<div class="totalNum">
			<span>奖励个数</span>
			<p><input type="number" placeholder="填写数量" v-model="num"> 个</p>
		</div>
		<div class="upImg" v-if="page==2">
			<img id="upImg" src="__IMAGE__/upimg.png" alt="" @click="choosePic">
			<div>(建议使用宽高比例为2:1的图片)</div>
		</div>
		<div class="tuwen" v-if="page==2">
			<input type="text" placeholder="请填写完整的链接,如:http://www.baidu.com" v-model="url">
		</div>
		<div class="tuwen" v-if="page==2">
			<input type="text" placeholder="请填写图文说明" v-model="explain">
		</div>
		<div class="bigMoney" v-if="page==1">
			¥{{priceTrue | toFixed(priceTrue)}}
			<p class="serverPay">(需额外支付{{persent*100}}%的服务费)</p>
		</div>		
		<div class="bigMoney" v-if="page==2">
			¥{{priceTrue | toFixed(priceTrue)}}
			<p class="serverPay">(需额外支付{{persent2*100}}%的服务费)</p>
		</div>		
		<div class="picPlay" v-if="page==1">
			<span @click="flagke=true">图文红包,抢先体验</span>
		</div>
		<div class="picPlay" v-if="page==2">
			<span @click="page=1">返回普通红包</span>
		</div>
		<div class="toGet">
			<a href="{:U('user/withdraw')}" v-if="userInfo!=undefined">优先使用余额：{{userInfo.money | toFixed(userInfo.money)}}元</a>
		</div>
		<div class="ok" @click="submit">
			生成语音口令
		</div>
		<div class="src">
			<a href="{:U('red/record')}">查看记录</a>
			|
			<a href="{:U('question/index')}">常见问题</a>
		</div>
		<div class="tishi" :class="{tishiA:flag}">
			口令只能输入中文
		</div>
		<div class="box" v-if="flag2">
			<div>
				<p>提示</p>
				<p>{{tips}}</p>
				<p @click="iknow">我知道了</p>
			</div>
		</div>	
		<div class="box2" v-if="flagke">
			<div>
				<p>图文红包说明</p>
				<p>1.图文红包可以发一张图片以作广告宣传,可以填写完整的地址进行链接。<br>
				   2.当红包额数超过100元并分享给朋友时,您的图片将显示在分享信息中。
				</p>
				<p class="btn">
					<span @click="go">体验</span>
					<span @click="flagke = false">取消</span>
				</p>
			</div>
		</div>		
	</div>
	<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
	<script src="__JS__/vue.min.js"></script>
	<script src="__JS__/common.min.js"></script>
	<script>
		var app = new Vue({
			el: "#app",
			data: {
				wxdata: '',     //公众号信息
				type: 0,  
				price: '',      //红包金额
				priceTrue: '',  //显示实际支付金额
				priceTrue2: '', //实际支付金额-余额
				text: '',       //口令
				num: '',        //红包个数
				flag: false,    //是否是中文
				tips: '',       //弹出框提示内容
				flag2: false,   //是否要弹出弹出框
				flag3: false,   //广告
				paying: true,   //防止多次提交
				userInfo: '',  //用户信息
				payInfo: '',   //支付信息
				persent: '',  //服务费百分比
				persent2: '',  //图文服务费百分比
				path: '',    //图片路径
				serverId: '',  //图片serverId
				explain: '',   //图文说明
				url: '',   //图文链接
				hbId: '',   //红包id
				page: 1,  //页面
				flagke: false,   //显示图文说明
			},
			watch: {
				price: {
					handler: function () { 
						if(this.page == 1) {
							this.priceTrue = Number(this.price*(1+Number(this.persent))).toFixed(2);
						}else {
							this.priceTrue = Number(this.price*(1+Number(this.persent2))).toFixed(2);
						}
						if(this.price == 1) {
							this.type = 1;
						}else if(this.price == 5) {
							this.type = 2;
						}else if(this.price == 10) {
							this.type = 3;
						}else if(this.price == 50) {
							this.type = 4;
						}else {
							this.type = 0;
						}
					},
					deep: true
				},
			},
			computed: {

			},
			mounted: function() {
				var that = this;				
				var url = location.href;
				// that.hw();    	
				if(url.indexOf('?')!=-1) {
					location.href = url.split('?')[0]
				}
				// 获取红包手续费
				$.ajax({
					url: '{:U('red/commission')}',
					type: 'post',
					data: {},
					success: function(data) {
						if (data.code == 200) {
							console.log(JSON.stringify(data))
							that.persent = data.data.service_fee;
							that.persent2 = data.data.img_fee;
						} else {
							alert(data.msg);
						}
						
					},
					error: function() {

					}
				})
				// 获取用户信息
				$.ajax({
					url: '{:U('user/info')}',
					type: 'post',
					data: {},
					dataType: 'json',
					success: function(data) {
						if (data.code == 200) {
							that.userInfo = data.data;
							console.log(that.userInfo);
						} else {
							alert(data.msg);
						}
					},
					error: function() {

					}
				})
				$.ajax({
					url: '{:U('setting/wxJsSDK')}',
					type: 'post',
					data: {
						url: url,
						code: 1
					},
					success: function(data) {
						if (data.code != 200) {
							alert(data.msg);
							return false;
						}
						that.wxdata = data.data;
						wx.config({
						    debug: false, 
						    appId: that.wxdata.appId, 
						    timestamp: that.wxdata.timestamp, 
						    nonceStr: that.wxdata.nonceStr, 
						    signature: that.wxdata.signature,
						    jsApiList: [
						    	"onMenuShareTimeline",   
								"onMenuShareAppMessage",  
								"chooseImage",     
								"previewImage",   
								"uploadImage",     
								"startRecord",     
								"stopRecord",      
								"onVoiceRecordEnd", 
								"playVoice",       
								"uploadVoice",     
						    ] 
						});

						wx.ready(function(){
							var url2 = url.split('sendPackage2').join('sendPackage')
							wx.onMenuShareAppMessage({
								title: '口令红包等你来抢', 
								desc: '口令红包 说对算你赢', 
								link: url2, 
								imgUrl: 'http://sfmhb.shanfengmao.com/logo.png', 
								type: '', 
								dataUrl: '', 
								success: function () { 

								},
								cancel: function () { 
							        
							    }
							});
							wx.onMenuShareTimeline({
								title: '口令红包等你来抢', 
								link: url2, 
								imgUrl: 'http://sfmhb.shanfengmao.com/logo.png', 
								success: function () { 

								},
								cancel: function () { 
							        
							    }
							});
						});
						wx.error(function(res){
							alert("调用失败")
						});
					},
					error: function() {

					}
				})
				
			},
			methods: {
				isChain: function() {
					var that = this;
					var str = this.text;				
					var reg = /^[\u4E00-\u9FA5]+$/; 
					if(!reg.test(str)){ 
						that.flag = true;
						var arr = str.split('');
						for(var i=0;i<arr.length;i++) {
							if(!reg.test(arr[i])) {
								arr[i] = '';
							}
						}
						this.text = arr.join('');
						setTimeout(function() {
							that.flag = false;
						},3000)
						return false; 
					} 
					return true; 
				},
				money: function() {
					var that = this;
					// 没有输入金额时默认1元
					if(this.price == '' | this.price < 1) {
						this.price = 1;
					}
					// 红包个数 1-5000
					if(this.num == '' | this.num >5000 | this.num < 1) {
						this.tips = '请输入1-5000的红包个数';
						this.num = 1;
						this.flag2 = true;
						return false;
					}
					if(this.serverId == ''&&this.page==2) {
						this.tips = '请选择图片';
						this.flag2 = true;
						return false;
					}
					var regExp = /^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/;
					if (!(this.url.match(regExp))&&this.page==2&&this.url != '') {
						this.tips = '请填写正确的地址链接';
						this.flag2 = true;
						return false;
					}
					// 每个红包奖励不低于0.50元
					// if(this.price / this.num < .5) {						
					// 	this.tips = '每人奖励不低于0.50元';
					// 	this.flag2 = true;
					// 	return false;
					// }			
					// 余额足够支付时
					if(Number(that.userInfo.money)>=that.priceTrue) {
						// 发给后台改变余额
						if(that.page==2) {
							$.ajax({
								type: 'post',
								url: '{:U('api/imgUpload')}',
								data: {
									media_id: that.serverId,
									type: 'img'
								},
								success: function(data){
									if(data.code == 200) {
										that.path = data.data.image;
										enough()
									}
								},
								error: function() {

								}
							})
						}else {
							enough()
						}
						return false;
					}else if(Number(that.userInfo.money)>0&&Number(that.userInfo.money)<that.priceTrue) {
						that.priceTrue2 = that.priceTrue - Number(that.userInfo.money);
					}else if(Number(that.userInfo.money)==0){
						that.priceTrue2 = that.priceTrue;
					}					
					// 点击支付后再上传图片
					if(that.page == 2) {
						$.ajax({
							type: 'post',
							url: '{:U('api/imgUpload')}',
							data: {
								media_id: that.serverId,
								type: 'img',
							},
							success: function(data){
								if(data.code == 200) {
									that.path = data.data.image;
									topay()
								}else{
									alert(data.msg)
								}
							},
							error: function() {

							}
						})
					}else {
						topay()
					}
			    	// 余额足够支付
			    	function enough() {
			    		$.ajax({
			    			type: 'post',
			    			url: '{:U('red/create')}',
			    			data: {
			    				money: that.price,
			    				title: that.text,
			    				number: that.num,
			    				img: that.path,								
			    				url: that.url,
			    				fee: that.priceTrue,
			    				content: that.explain,
			    				type: that.page
			    			},
			    			success: function(data) {
			    				if (data.code != 200) {
			    					alert(data.msg);
			    					return false;
			    				}
			    				if (data.data.is_pay == 1) {
			    					that.userInfo.money = Number(that.userInfo.money) - that.priceTrue;
			    					location.href = '{:U('red/find')}' + '?id=' + data.data.red_id;
			    				} else {
			    					
			    				}
			    			},
			    			error: function() {

			    			}
			    		})
			    	}
			    	// 调用微信支付
			    	function topay() {
			    		$.ajax({
			    			type: 'post',
			    			url: '{:U('red/create')}',
			    			data: {
			    				user_id: that.userInfo.id,
			    				money: Number(that.price).toFixed(2),
			    				title: that.text,
			    				number: that.num,
			    				img: that.path,
			    				url: that.url,
			    				fee: that.price,
			    				content: that.explain,
			    				type: that.page
			    			},
			    			success: function(data) {
			    				if (data.code != 200) {
			    					alert(data.msg);return false;
			    				}
			    				that.payInfo = data.data.js_api_parameters;	
			    				that.hbId = data.data.red_id;	
			    				callpay()
			    			},
			    			error: function() {

			    			}
			    		})
			    	}
					//调用微信JS api 支付
					function jsApiCall(){
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest',
							{
								"appId":that.payInfo.appId,     
								"timeStamp":that.payInfo.timeStamp,          
								"nonceStr":that.payInfo.nonceStr, 
								"package":that.payInfo.package,     
								"signType":that.payInfo.signType,        
								"paySign":that.payInfo.paySign 
							},
							function(res){
								if(res.err_msg=="get_brand_wcpay_request:ok"){
									location.href = '{:U('red/find')}' + '?id=' + that.hbId;
								}else if(res.err_msg=="get_brand_wcpay_request:cancel"){
									
								}else {
									alert('支付失败');
								}
							}
							);
					}
					function callpay(){
						if (typeof WeixinJSBridge == "undefined"){
							if( document.addEventListener ){
								document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
							}else if (document.attachEvent){
								document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
								document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
							}
						}else{
							jsApiCall();
						}
					}
				},
				iknow: function() {
					this.flag2 = false;
				},
				// 口令检验
				Input: function() {
					this.isChain();
				},
				// 图文红包
				go: function() {
					this.page = 2;
					this.flagke = false;
				},
				// 生成口令红包
				submit: function() {
					var that = this;
					var str = this.text;
					if(str == '') {
						str = '谢谢老板';
						that.text = str;
					}					
					if(this.paying) {
						this.paying = false;
						this.money();
						setTimeout(function(){
							that.paying = true;
						},3000)
					}
				},
				// 选择图片
				choosePic: function() {					
					var that = this;
					wx.chooseImage({
						count: 1, 
						sizeType: ['original', 'compressed'], 
						sourceType: ['album', 'camera'], 
						success: function (res) {	
							that.pic = res.localIds[0]; 
							$('.upImg img').attr('src',that.pic); 
							that.upImg();  
							$('#upImg').css('width', '100%').css('height','160px'); 
						}
					});
				},
				upImg: function() {
					var that = this;
					// 上传图片接口
					wx.uploadImage({
						localId: that.pic, 
						isShowProgressTips: 1, 
						success: function (res) {
							that.serverId = res.serverId;  
						}
					});
				}
			},
			filters:{
				toFixed:function (price) {
					return Number(price).toFixed(2);
				},
			}
		})
	</script>
</body>
</html>